<template>
	<view class="content">
		<u--image
		    :showLoading="true"
		    src="../../../static/logo.png"
		    width="80px"
		    height="80px"
		    @click="click"
		  ></u--image>
		<view class="login-btn">
			<u-button type="primary" @click="handleLogin" :loading="loading" loadingText="登录中....">微信一键登录</u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	
	import { wechatLogin } from '@/api/auth/user';
	
	export default {
		data() {
			return {
				title: 'Hello',
				loading: false
			}
		},
		onLoad() {

		},
		methods: {
			// 同步处理
			async handleLogin(){
				// 1、按钮状态更改
				this.loading = true;
				
				// 2、调用小程序的login，返回code
				const { code } = await uni.login({
					provider: 'weixin'
				})
				
				// 3、调用后端的接口，传入code，执行后端登录操作
				const res = await wechatLogin(code);
				if(res.code == 200){
					uni.setStorageSync("token",res.token)
					uni.setStorageSync("userInfo",res.userInfo)
					// 判断用户是否绑定了手机号
					if(!res.userInfo.phone){
						// 跳转到绑定手机号的页面
						uni.navigateTo({
							url: '/pages/bindphone/bindphone'
						})
					}else{
						// 跳转到模拟面试页面
						uni.navigateTo({
							url: '/pages/interview/interview'
						})
					}
				}else{
					// 提示登录失败
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: "登录失败"
					  });
				}
				
				this.loading = false;
			}
		},
		onLoad() {
			// 判断是否登录过
			if(uni.getStorageSync("token")){
				if(uni.getStorageSync("userInfo").phone){
					uni.navigateTo({
						url: '/pages/interview/interview'
					})
				}else{
					uni.navigateTo({
						url: '/pages/bindphone/bindphone'
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.content{
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		margin-top: 300rpx;
	}
	.login-btn{
		margin-top: 100rpx;
		width:300rpx;
	}
</style>
